package com.example.sys.attachment.controller;

import com.example.core.controller.BaseCoreController;
import com.example.core.utils.Result;
import com.example.sys.attachment.po.SysAttachment;
import com.example.sys.attachment.service.SysAttachmentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

@RequestMapping(value = "sysAttachment")
@RestController
public class SysAttachmentController extends BaseCoreController<SysAttachmentService> {

    Logger logger = LoggerFactory.getLogger(getClass());


    /***
     * 上传文件
     * @param file
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @PostMapping(value = "upload")
    public Result upload(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        try {
            SysAttachment sysAttachment = this.getService().upload(file, request, response);
            return Result.success(sysAttachment);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /***
     * 文件下载
     * @param id
     * @param response
     */
    @ResponseBody
    @GetMapping(value = "download")
    public void download(@RequestParam String id, HttpServletResponse response) {
        OutputStream outputStream = null;
        try {
            if (id != null) {
                SysAttachment sysAttachment = this.getService().getById(id);
                if (sysAttachment != null) {
                    String filename = sysAttachment.getName();
                    byte[] bytes = this.getService().read(sysAttachment.getId());
                    response.setCharacterEncoding("UTF-8");
                    response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
                    response.addHeader("Content-Length", String.valueOf(bytes.length));
                    outputStream = new BufferedOutputStream(response.getOutputStream());
                    response.setContentType("application/octet-stream");
                    outputStream.write(bytes);
                    outputStream.flush();
                }
            }
        } catch (Exception e) {
            logger.error("文件下载报错: {}", e.getMessage());
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
